package com.beemans.common.ext

import java.math.RoundingMode
import java.text.DecimalFormat

/**
 * @author tiamosu
 * @date 2021/3/12
 */
/**
 * 描述：数据格式转化
 *
 * @param scale 保留几位小数
 * @param unit  单位
 * @param def   当数值为 NaN 时，默认显示
 * @param isGroupingUsed 是否在千分位显示逗号
 * @param isHalfUp 是否进行四舍五入
 * @param isCutZero 是否去掉小数后面多余的0
 */
fun Double.format(
    scale: Int = 2,
    unit: String? = null,
    def: Any? = null,
    isGroupingUsed: Boolean = false,
    isHalfUp: Boolean = false,
    isCutZero: Boolean = false
): String {
    val newUnit = unit ?: ""
    if (java.lang.Double.isNaN(this)) {
        val newDef = def ?: "-"
        return newDef.toString() + newUnit
    }

    var newValue = DecimalFormat(getPattern(scale)).also {
        it.roundingMode = if (isHalfUp) RoundingMode.HALF_UP else RoundingMode.DOWN
        if (isGroupingUsed) {
            it.isGroupingUsed = true
            it.groupingSize = 3
        }
    }.format(this)

    if (isCutZero && newValue.indexOf(".") > 0) {
        //去掉多余的0
        newValue = newValue.replace("0+?$".toRegex(), "")
        //如最后一位是.则去掉
        newValue = newValue.replace("[.]$".toRegex(), "")
    }
    return newValue + newUnit
}

private fun getPattern(scale: Int): String {
    val builder = StringBuilder("0")
    for (i in 0 until scale) {
        if (i == 0) {
            builder.append(".0")
        } else {
            builder.append("0")
        }
    }
    return builder.toString()
}